package com.hmdp.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopTypeMapper shopTypeMapper;
    @Override
    public List<ShopType> queryAll() {
        //1查询redis缓存
        Set<String> shopTYpeItems = stringRedisTemplate.opsForSet().members(CACHE_SHOP_TYPE_KEY);
        if (!shopTYpeItems.isEmpty()) {

            //2查到，直接返回
            List<ShopType> shopTypes = new ArrayList<>();
            for (String shopTYpeItem : shopTYpeItems) {
                ShopType shopTypeItem = JSONUtil.toBean(shopTYpeItem, ShopType.class);
                shopTypes.add(shopTypeItem);
            }
            return shopTypes;
        }
        //3没查到，查询数据库
        List<ShopType> shopTypes = shopTypeMapper.selectList(null);
        if (!shopTypes.isEmpty()) {
            //4查到，存放到redis并返回

            stringRedisTemplate.opsForSet().add(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypes));
            return shopTypes;
        }
        //5没查到，返回
        return Collections.emptyList();
    }
}
